package mdm.led.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import mdm.led.common.AjaxResponse;
import mdm.led.common.BaseController;
import mdm.led.common.Constant;
import mdm.led.entity.Permission;
import mdm.led.entity.Role;
import mdm.led.entity.User;
import mdm.led.entity.Wuser;
import mdm.led.log.OperationLog;
import mdm.led.service.IRoleService;
import mdm.led.service.UserService;
import mdm.led.util.BeanId;
import mdm.led.util.MD5;
import mdm.led.util.session.TokenSession;
import mdm.led.util.session.TokenSessionManager;
import mdm.led.util.session.TokenUtil;
import java.util.List;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Controller
@RequestMapping(value = "login")
@Api(description = "登录模块")
public class LoginController extends BaseController {
	private static final Logger LOGGER = LoggerFactory.getLogger(LoggerFactory.class);

	@Autowired
	private UserService userService;

	@Autowired
	private IRoleService roleService;

	@ApiOperation(value = "WEB用户登录", notes = "请求参数:<br>" + "username 用户名<br>" + "password 密码")
	@OperationLog(operationModule = "登录模块", operationFunction = "登录")
	@ResponseBody
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public AjaxResponse login(@RequestBody Wuser user) {

		LOGGER.info("=======login========");
		LOGGER.info("username={" + user.getcUsername() + "},password={+" + user.getcPassword() + "}");

		try {
			User accountInfo = userService.selectByUsername(user.getcUsername());

			if (accountInfo == null) {
				return AjaxResponse.reponseBody(Constant.FAIL_CODE, "用户名不存在!", null);
			}
			if (accountInfo.getState() == 0) {
				return AjaxResponse.reponseBody(Constant.FAIL_CODE, "该用户已被禁用!", null);
			}
			if (!MD5.getStandardMd5(user.getcPassword()).equals(accountInfo.getcPassword())) {
				return AjaxResponse.reponseBody(Constant.FAIL_CODE, "用户名或密码输入错误!", null);
			}

			UsernamePasswordToken token = new UsernamePasswordToken(user.getcUsername(),
					MD5.getStandardMd5(user.getcPassword()));
			Subject subject = SecurityUtils.getSubject();
			subject.login(token);

			TokenSession session = new TokenSession();

			session.setAccountId(accountInfo.getcUserId());
			session.setAccountName(accountInfo.getcUsername());
			session.setNickName(accountInfo.getcNickname());
			session.setCreateTime(System.currentTimeMillis());
			session.setLatestActiveTime(System.currentTimeMillis());

			// 获取用户操作权限，保存到session
			User userpermission = userService.selectByRolePermission(accountInfo.getcUserId());
			
			if (accountInfo.getRoleId() == 1 || accountInfo.getRoleId() == 3 || accountInfo.getRoleId() == 2) {
				// 获取一二级权限结构
				Role r = new Role();
				r.setcRoleId(userpermission.getRoleId());
				List<Permission> permissionList = roleService.initPermissonList(r);
				JSONArray functionPermissions = new JSONArray();
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("permissionDetailUrl", r.getRolepermissionlist());
				functionPermissions.add(jsonObject);

				session.setRolePermission(functionPermissions);
				// 生成token，创建会话
				String sessionToken = BeanId.generateUUId();
				// sessionKey
				session.setToken(sessionToken);
				TokenSessionManager.getInstance().addDomainTokenSession(session);
				JSONObject result = new JSONObject();

				result.put("roleId", accountInfo.getRoleId());
				result.put("token", sessionToken);
				result.put("permissionList", permissionList);
				// result.put("permissionDetails", functionPermissions);
				return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, result);
			} else {
				return AjaxResponse.reponseBody(Constant.FAIL_CODE, "此用户无权限!", null);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, null);
		}
	}

	@ApiOperation(value = "用户登录-APP", notes = "请求参数:<br>" + "username 用户名<br>" + "password 密码")
	@ResponseBody
	@RequestMapping(value = "/applogin", method = RequestMethod.POST)
	public AjaxResponse appLogin(@RequestParam("username") String username, @RequestParam("password") String password) {
		try {
			User accountInfo = userService.selectByUsername(username);
			
			if (accountInfo == null || accountInfo.getState() == 2) {
				return AjaxResponse.reponseBody(Constant.FAIL_CODE, "用户名不存在!", null);
			}
			
			if(accountInfo.getcUsername().equals("admin")){
				return AjaxResponse.reponseBody(Constant.FAIL_CODE, "您无权限进入!", null);
			}

			if (!MD5.getStandardMd5(password).equals(accountInfo.getcPassword())) {
				return AjaxResponse.reponseBody(Constant.FAIL_CODE, "用户名或密码输入错误!", null);
			}
			if (accountInfo.getState() == 0) {
				return AjaxResponse.reponseBody(Constant.FAIL_CODE, "该用户已被禁用!", null);
			}
			
			
			UsernamePasswordToken token = new UsernamePasswordToken(username, MD5.getStandardMd5(password), "app");
			Subject subject = SecurityUtils.getSubject();
			subject.login(token);

			TokenSession session = new TokenSession();

			session.setAccountId(accountInfo.getcUserId());
			session.setAccountName(accountInfo.getcUsername());
			session.setNickName(accountInfo.getcNickname());
			session.setCreateTime(System.currentTimeMillis());
			session.setLatestActiveTime(System.currentTimeMillis());

			// 生成token，创建会话
			String sessionToken = BeanId.generateUUId();
			// sessionKey

			session.setToken(sessionToken);
			TokenSessionManager.getInstance().addDomainTokenSession(session);
			JSONObject result = new JSONObject();
			result.put("userInfo", accountInfo);
			result.put("token", sessionToken);

			return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, result);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, null);
		}
	}

	@ApiOperation(value = "用户登出", notes = "请求参数:<br>" + "token 会话id")
	@OperationLog(operationModule = "登录模块", operationFunction = "登出")
	@ResponseBody
	@RequestMapping(value = "/logout/{token}", method = RequestMethod.GET)
	public AjaxResponse logout(@PathVariable String token) {
		try {
			// 退出登录，移除会话
			Integer userId = TokenUtil.getUserId(token);
			Subject subject = SecurityUtils.getSubject();
			subject.logout();
			TokenSessionManager.getInstance().removeDomainTokenSession(token);
			JSONObject result = new JSONObject();
			result.put("userId", userId);
			return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, result);
		} catch (Throwable e) {
			LOGGER.error("", e);
			return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, null);
		}
	}

}
